/**
 * @fileOverview The "link" plugin.
 */
VED.plugins.add( 'link', {
   requires: 'dialog,fakeobjects',
   lang: 'en,ru', // %REMOVE_LINE_CORE%
   icons: 'anchor,anchor-rtl,link,unlink', // %REMOVE_LINE_CORE%
   onLoad: function() {
      // Add the CSS styles for anchor placeholders.
      var baseStyle = 'background:url(' + VED.getUrl( this.path + 'images/anchor.png' ) + ') no-repeat %1 center;' +
         'border:1px dotted #00f;';

      var template = '.%2 a.ved_anchor,' +
         '.%2 a.ved_anchor_empty' +
         ',.ved_editable.%2 a[name]' +
         ',.ved_editable.%2 a[data-ved-saved-name]' +
         '{' +
            baseStyle +
            'padding-%1:18px;' +
            // Show the arrow cursor for the anchor image (FF at least).
            'cursor:auto;' +
         '}' +
         ( VED.env.ie ? ( 'a.ved_anchor_empty' +
         '{' +
            // Make empty anchor selectable on IE.
            'display:inline-block;' +
         '}'
         ) : '' ) +
         '.%2 img.ved_anchor' +
         '{' +
            baseStyle +
            'width:16px;' +
            'min-height:15px;' +
            // The default line-height on IE.
            'height:1.15em;' +
            // Opera works better with "middle" (even if not perfect)
            'vertical-align:' + ( VED.env.opera ? 'middle' : 'text-bottom' ) + ';' +
         '}';

      // Styles with contents direction awareness.
      function cssWithDir( dir ) {
         return template.replace( /%1/g, dir == 'rtl' ? 'right' : 'left' ).replace( /%2/g, 'ved_contents_' + dir );
      }

      VED.addCss( cssWithDir( 'ltr' ) + cssWithDir( 'rtl' ) );
   },

   init: function( editor ) {
      var allowed = 'a[!href]',
         required = 'a[href]';

      if ( VED.dialog.isTabEnabled( editor, 'link', 'advanced' ) )
         allowed = allowed.replace( ']', ',accesskey,charset,dir,id,lang,name,rel,tabindex,title,type]{*}(*)' );
      if ( VED.dialog.isTabEnabled( editor, 'link', 'target' ) )
         allowed = allowed.replace( ']', ',target,onclick]' );

      // Add the link and unlink buttons.
      editor.addCommand( 'link', new VED.dialogCommand( 'link', {
         allowedContent: allowed,
         requiredContent: required
      } ) );
      editor.addCommand( 'anchor', new VED.dialogCommand( 'anchor', {
         allowedContent: 'a[!name,id]',
         requiredContent: 'a[name]'
      } ) );
      editor.addCommand( 'unlink', new VED.unlinkCommand() );
      editor.addCommand( 'removeAnchor', new VED.removeAnchorCommand() );

      editor.setKeystroke( VED.CTRL + 76 /*L*/, 'link' );

      if ( editor.ui.addButton ) {
         editor.ui.addButton( 'Link', {
            label: editor.lang.link.toolbar,
            command: 'link',
            toolbar: 'links,10'
         });
         // editor.ui.addButton( 'Unlink', {
            // label: editor.lang.link.unlink,
            // command: 'unlink',
            // toolbar: 'links,20'
         // });
         editor.ui.addButton( 'Anchor', {
            label: editor.lang.link.anchor.toolbar,
            command: 'anchor',
            toolbar: 'links,30'
         });
      }

      // VED.dialog.add( 'link', this.path + 'dialogs/link.js' );
      // VED.dialog.add( 'anchor', this.path + 'dialogs/anchor.js' );

      editor.on( 'doubleclick', function( evt ) {
         var element = VED.plugins.link.getSelectedLink( editor ) || evt.data.element;

         if ( !element.isReadOnly() ) {
            if ( element.is( 'a' ) ) {
               evt.data.dialog = ( element.getAttribute( 'name' ) && ( !element.getAttribute( 'href' ) || !element.getChildCount() ) ) ? 'anchor' : 'link';
               editor.getSelection().selectElement( element );
            } else if ( VED.plugins.link.tryRestoreFakeAnchor( editor, element ) )
               evt.data.dialog = 'anchor';
         }
      });

      // If the "menu" plugin is loaded, register the menu items.
      if ( editor.addMenuItems ) {
         editor.addMenuItems({
            anchor: {
               label: editor.lang.link.anchor.menu,
               command: 'anchor',
               group: 'anchor',
               order: 1
            },

            removeAnchor: {
               label: editor.lang.link.anchor.remove,
               command: 'removeAnchor',
               group: 'anchor',
               order: 5
            },

            link: {
               label: editor.lang.link.menu,
               command: 'link',
               group: 'link',
               order: 1
            },

            unlink: {
               label: editor.lang.link.unlink,
               command: 'unlink',
               group: 'link',
               order: 5
            }
         });
      }

      // If the "contextmenu" plugin is loaded, register the listeners.
      if ( editor.contextMenu ) {
         editor.contextMenu.addListener( function( element, selection ) {
            if ( !element || element.isReadOnly() )
               return null;

            var anchor = VED.plugins.link.tryRestoreFakeAnchor( editor, element );

            if ( !anchor && !( anchor = VED.plugins.link.getSelectedLink( editor ) ) )
               return null;

            var menu = {};

            if ( anchor.getAttribute( 'href' ) && anchor.getChildCount() )
               menu = { link: VED.TRISTATE_OFF, unlink: VED.TRISTATE_OFF };

            if ( anchor && anchor.hasAttribute( 'name' ) )
               menu.anchor = menu.removeAnchor = VED.TRISTATE_OFF;

            return menu;
         });
      }
   },

   afterInit: function( editor ) {
      // Register a filter to displaying placeholders after mode change.

      var dataProcessor = editor.dataProcessor,
         dataFilter = dataProcessor && dataProcessor.dataFilter,
         htmlFilter = dataProcessor && dataProcessor.htmlFilter,
         pathFilters = editor._.elementsPath && editor._.elementsPath.filters;

      if ( dataFilter ) {
         dataFilter.addRules({
            elements: {
               a: function( element ) {
                  var attributes = element.attributes;
                  if ( !attributes.name )
                     return null;

                  var isEmpty = !element.children.length;

                  if ( VED.plugins.link.synAnchorSelector ) {
                     // IE needs a specific class name to be applied
                     // to the anchors, for appropriate styling.
                     var ieClass = isEmpty ? 'ved_anchor_empty' : 'ved_anchor';
                     var cls = attributes[ 'class' ];
                     if ( attributes.name && ( !cls || cls.indexOf( ieClass ) < 0 ) )
                        attributes[ 'class' ] = ( cls || '' ) + ' ' + ieClass;

                     if ( isEmpty && VED.plugins.link.emptyAnchorFix ) {
                        attributes.contenteditable = 'false';
                        attributes[ 'data-ved-editable' ] = 1;
                     }
                  } else if ( VED.plugins.link.fakeAnchor && isEmpty )
                     return editor.createFakeParserElement( element, 'ved_anchor', 'anchor' );

                  return null;
               }
            }
         });
      }

      if ( VED.plugins.link.emptyAnchorFix && htmlFilter ) {
         htmlFilter.addRules({
            elements: {
               a: function( element ) {
                  delete element.attributes.contenteditable;
               }
            }
         });
      }

      if ( pathFilters ) {
         pathFilters.push( function( element, name ) {
            if ( name == 'a' ) {
               if ( VED.plugins.link.tryRestoreFakeAnchor( editor, element ) || ( element.getAttribute( 'name' ) && ( !element.getAttribute( 'href' ) || !element.getChildCount() ) ) ) {
                  return 'anchor';
               }
            }
         });
      }
   }
});

VED.plugins.link = {

   getSelectedLink: function( editor ) {
      var selection = editor.getSelection();
      var selectedElement = selection.getSelectedElement();
      if ( selectedElement && selectedElement.is( 'a' ) )
         return selectedElement;

      var range = selection.getRanges( true )[ 0 ];

      if ( range ) {
         range.shrink( VED.SHRINK_TEXT );
         return editor.elementPath( range.getCommonAncestor() ).contains( 'a', 1 );
      }
      return null;
   },

   fakeAnchor: VED.env.opera || VED.env.webkit,

   synAnchorSelector: VED.env.ie,

   emptyAnchorFix: VED.env.ie && VED.env.version < 8,

   tryRestoreFakeAnchor: function( editor, element ) {
      if ( element && element.data( 'ved-real-element-type' ) && element.data( 'ved-real-element-type' ) == 'anchor' ) {
         var link = editor.restoreRealElement( element );
         if ( link.data( 'ved-saved-name' ) )
            return link;
      }
   }
};

// TODO Much probably there's no need to expose these as public objects.

VED.unlinkCommand = function() {};
VED.unlinkCommand.prototype = {
   exec: function( editor ) {
      var style = new VED.style( { element:'a',type:VED.STYLE_INLINE,alwaysRemoveElement:1 } );
      editor.removeStyle( style );
   },

   refresh: function( editor, path ) {
      // Despite our initial hope, document.queryCommandEnabled() does not work
      // for this in Firefox. So we must detect the state by element paths.

      var element = path.lastElement && path.lastElement.getAscendant( 'a', true );

      if ( element && element.getName() == 'a' && element.getAttribute( 'href' ) && element.getChildCount() )
         this.setState( VED.TRISTATE_OFF );
      else
         this.setState( VED.TRISTATE_DISABLED );
   },

   contextSensitive: 1,
   startDisabled: 1,
   requiredContent: 'a[href]'
};

VED.removeAnchorCommand = function() {};
VED.removeAnchorCommand.prototype = {
   exec: function( editor ) {
      var sel = editor.getSelection(),
         bms = sel.createBookmarks(),
         anchor;
      if ( sel && ( anchor = sel.getSelectedElement() ) && ( VED.plugins.link.fakeAnchor && !anchor.getChildCount() ? VED.plugins.link.tryRestoreFakeAnchor( editor, anchor ) : anchor.is( 'a' ) ) )
         anchor.remove( 1 );
      else {
         if ( ( anchor = VED.plugins.link.getSelectedLink( editor ) ) ) {
            if ( anchor.hasAttribute( 'href' ) ) {
               anchor.removeAttributes( { name:1,'data-ved-saved-name':1 } );
               anchor.removeClass( 'ved_anchor' );
            } else
               anchor.remove( 1 );
         }
      }
      sel.selectBookmarks( bms );
   },
   requiredContent: 'a[name]'
};

VED.tools.extend( VED.config, {
   linkShowAdvancedTab: true,
   linkShowTargetTab: true
});





